using System;
using System.Drawing;
using System.Collections.Generic;
using Clandestine.Graphics;
using Clandestine.Engines.Field;
using Clandestine.Base;

namespace Shlick
{
	public class TilePasterTool : Tool	
	{
		public MapDocument MapDocument { get; private set; } 
        public ToolManager ToolManager { get { return this.MapDocument.ToolManager; } } 
        public Map Map { get { return this.ToolManager.Map; } } 
        public override string Name { get { return "Move/Paste Tiles"; } }
        public override event ToolCompleteHandler ToolComplete;

		private Tile?[,] tiles;

        /// <summary>
        /// Current position of the mouse.
        /// </summary>
        private Point currentPosition = new Point();
	
        public TilePasterTool(MapDocument mapDocument)
        {
            this.MapDocument = mapDocument;
        }

        public override void Activated(params object[] args)
        {
			tiles = (Tile?[,])args[0];
        }

        public override void Deactivated()
        {
            if (this.ToolManager.ActiveLayer == null)
        		return;
        		
        	this.MapDocument.ToolManager.ActiveLayer.ClearTemporaryTiles();
        }
        
        public override void LayerChanged(Layer oldLayer)
		{
			if (oldLayer != null)
				oldLayer.ClearTemporaryTiles();
		}

        public override void MouseDownLeft(int mouseX, int mouseY, int tileX, int tileY)
        {
       		if (this.ToolManager.ActiveLayer == null)
        		return;
        		
            this.MapDocument.CommandManager.Do(PaintTilesCommand.PaintTiles(this.ToolManager.ActiveLayer, tiles, new Point(tileX, tileY), false));
			this.ToolManager.ActiveLayer.ClearTemporaryTiles();
			
			if (this.ToolComplete != null)
				this.ToolComplete();
        }

        public override void MouseDownRight(int mouseX, int mouseY, int tileX, int tileY)
        {
       		if (this.ToolManager.ActiveLayer != null)
        		this.ToolManager.ActiveLayer.ClearTemporaryTiles();
			if (this.ToolComplete != null)
				this.ToolComplete();
        }
		
        public override void MouseMove(int mouseX, int mouseY, int tileX, int tileY)
        {
        	if (this.ToolManager.ActiveLayer == null)
        		return;
			
			if (currentPosition.X != tileX || currentPosition.Y != tileY)
			{
				currentPosition = new Point(tileX, tileY);
				
				this.ToolManager.ActiveLayer.ClearTemporaryTiles();
				PaintTilesCommand.PaintTiles(this.ToolManager.ActiveLayer, tiles, currentPosition, true);
			}
        }

    }
}

